package pe.isil.sco.proyecto.util;

import java.util.*;
import javax.naming.*;
import javax.sql.*;

public class Conexion implements java.io.Serializable {

    private InitialContext ic = null;
    private Map cache = null;
    private static Conexion instance;
    private String dataSourceName = "jdbc/combopon";

    private Conexion() throws NamingException {
        try {
            ic = new InitialContext();
            cache = Collections.synchronizedMap(new HashMap());
        } catch (NamingException ne) {

            throw ne;
        }
    }

    /**
     * Constructor privado
     *
     * @param iCtx
     */
    private Conexion(InitialContext iCtx) {
        ic = iCtx;
    }

    /**
     *
     * Si no hay instancia la crea y si hay la devuelve
     *
     * @return
     * @throws NamingException
     */
    public static Conexion getInstance() throws NamingException {
        if (instance == null) {
            instance = new Conexion();
        }
        return instance;
    }

    public static InitialContext getInitialContext() throws NamingException {
        return new InitialContext();
    }

    public DataSource getDataSource() throws NamingException {

        DataSource dataSource = null;
        try {
            if (cache.containsKey(dataSourceName)) {
                dataSource = (DataSource) cache.get(dataSourceName);

            } else {
                dataSource = (DataSource) ic.lookup(dataSourceName);
                cache.put(dataSourceName, dataSource);

            }
        } catch (NamingException nex) {
            throw new NamingException();

        } catch (Exception ex) {
            throw new NamingException();
        }
        return dataSource;
    }
}
